package com.homedo.odin.solution.service;

import com.alibaba.fastjson.JSON;
import com.homedo.common.redis.service.RedisService;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.odin.solution.enumcode.other.RedisKeyEnum;
import com.homedo.odin.solution.model.dto.LevelRule;
import com.homedo.odin.solution.model.dto.ScoreLevelPrivilege;
import com.homedo.odin.solution.model.entity.UserScoreLevel;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: zhaoxudong
 * @date: 2018/3/9 14:56
 * @Description:
 */
@Component
public class ScoreLevelServiceImpl {

    private final static Logger logger = LoggerFactory.getLogger(ScoreLevelServiceImpl.class);
    @Autowired
    UserScoreLevelServiceImpl levelService;
    @Autowired
    RedisService redisService;

    /**
     * 获取积分等级规则
     */
    public List<LevelRule> getRuleList() {
        return BeanUtils.batchTransform(LevelRule.class, getPrivilegeList());
    }


    /**
     * 根据积分获取当前积分等级
     */
    public LevelRule getScoreLevelByScore(Integer total) {
        List<LevelRule> levels = getRuleList();
        if (total <= 0) {
            return levels.get(0);
        }
        Collections.reverse(levels);
        for (LevelRule level : levels) {
            if (total >= level.getScore()) {
                return level;
            }
        }
        return null;
    }

    /**
     * 获取积分等级特权
     */
    public List<ScoreLevelPrivilege> getPrivilegeList() {
        //查询redis
        List<ScoreLevelPrivilege> privilegeList = JSON
                .parseArray(JSON.toJSONString(redisService.get(RedisKeyEnum.score_level.name())),
                        ScoreLevelPrivilege.class);
        //如果redis中不存在，就查数据库，然后存入redis中
        if (privilegeList == null) {
            List<UserScoreLevel> scoreLevel = levelService.findAll();
            privilegeList = BeanUtils.batchTransform(ScoreLevelPrivilege.class, scoreLevel);
            if (!scoreLevel.isEmpty()) {
                //添加到redis中
                try {
                    redisService.set(RedisKeyEnum.score_level.name(), privilegeList);
                } catch (Exception e) {
                    logger.error("积分等级插入redis出错", e);
                }
            }
        }
        return privilegeList;
    }


}
